<template>
    <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品添加</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图区 -->
      <el-card>
        <!-- 提示信息条 -->
        <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon>
        </el-alert>
        <!-- 步骤条 -->
        <el-steps :space="200" :active="activeName - 0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- 标签区 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
          <el-tabs :tab-position="'left'" v-model="activeName" :before-leave="beforeTabLeave" @tab-click="tabClicked">
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input type="number" v-model="addForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input type="number" v-model="addForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input type="number" v-model="addForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <!-- 级联选择器 -->
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props="cascaderProp"
                  expandTrigger='hover'
                  clearable
                  @change="handleChange"></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <!-- 动态参数表单 -->
              <el-form-item :label="items.attr_name" v-for="items in this.manyTableData" :key="items.attr_id">
                <el-checkbox-group v-model="items.attr_vals">
                  <el-checkbox :label="item" v-for="(item,k) in items.attr_vals" :key="k" border></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item :label="item.attr_name" v-for="item in this.onlyTableData" :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                :action="uploadURL"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headerObj"
                :on-success="handleSuccess"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器 -->
              <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            </el-tab-pane>
            <el-tab-pane label="完成" name="5">
              <!-- 添加商品按钮 -->
              <el-button type="primary" @click="add">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-card>
      <!-- 图片预览区 -->
      <el-dialog title="提示" :visible.sync="previewPic" width="50%">
        <img :src="previewPath" alt="#" width="100%">
      </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'add',
  data () {
    return {
      activeName: 0,
      /* 添加商品的表单数据 */
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        /* 商品分类所属的数组 */
        goods_cat: [],
        /*  图片数组 */
        pics: [],
        /* 商品的详情描述 */
        goods_introduce: '',
        /* 商品参数 */
        attrs: []
      },
      /* 商品添加表单校验 */
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选则商品分类', trigger: 'blur' }]
      },
      /* 商品分类列表 */
      cateList: [],
      cascaderProp: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      /* 商品动态参数 */
      manyTableData: [],
      /* 商品静态属性 */
      onlyTableData: [],
      /* 图片上传路径 */
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      /* 图片上传组件的 headers 请求头对象 */
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      /* 图片响应的真实路径 */
      previewPath: '',
      /* 图片预览框 */
      previewPic: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    /* 获取商品分类列表 */
    async getCateList () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('商品分类获取失败！')
      }
      this.cateList = res.data
    },
    /* 级联选择器发生改变触发 */
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    /* 条件成立时 标签切换 */
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选则商品分类')
        return false
      }
    },
    /* 获取商品参数 属性 */
    async tabClicked () {
      /* 获取商品动态参数 '1' 获取商品静态属性 '2' */
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error('商品参数获取失败！')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeName === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) {
          return this.$message.error('商品属性获取失败！')
        }
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    /* 图片预览 */
    handlePreview (file) {
      this.previewPath = file.response.data.url
      this.previewPic = true
    },
    /* 图片移除 */
    handleRemove (file) {
      /* 获取图片临时路径 */
      const filePath = file.response.data.tmp_path
      /* 获取图片对应的索引值 pics中是以对象存储的 */
      const i = this.addForm.pics.findIndex(f => f.pic === filePath)
      /* 根据索引值 删除图片 */
      this.addForm.pics.splice(i, 1)
    },
    /* 监听图片上传成功事件 */
    handleSuccess (response) {
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    /* 添加商品 */
    add () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请将信息填写完整')
        /* 通过lodash进行cloneDeep深拷贝goods_cat 因为分类的双向绑定要求是数组 而上传是 ，分割 */
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        /* 处理动态参数和静态属性 并保存到 addForm */
        /* 动态参数 */
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        /* 静态属性 */
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        /* 保存到form */
        form.attrs = this.addForm.attrs
        /* 添加 */
        const { data: res } = await this.$http.post('/goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('商品添加失败！')
        }
        this.$router.push('/goods')
        return this.$message.success('商品添加成功')
      })
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
  .el-steps {
    margin: 13px auto;
  }
  .el-checkbox {
    margin: 0 10px 0 0!important;
    padding: 9px 5px!important;
    font-size: 13px!important;
  }
  .el-upload__tip {
    font-size: 12px;
    color: #999;
  }
</style>
